#include "Common.h"
#include "Sock/AppLibSock_Unix.hpp"

#include <signal.h>

APP_LIB_SOCK_s gstSrvSock = {.iSock = -1};
APP_LIB_SOCK_s gstCliSock = {.iSock = -1};


void signal_deal(int signo)
{
    printf("catch signo:%d, exit process\n", signo);

	AppLibSock_Close(&gstSrvSock);
	AppLibSock_Close(&gstCliSock);

	exit(-1);
}

void signal_register(void)
{
    signal(SIGHUP,  signal_deal);
    signal(SIGINT,  signal_deal);  //Ctrl + C
    signal(SIGQUIT, signal_deal);
    signal(SIGPIPE, signal_deal);
    signal(SIGALRM, signal_deal);
    signal(SIGTERM, signal_deal);
    signal(SIGSEGV, signal_deal);
    signal(SIGKILL, signal_deal);
}

int main (int argc, char **args)
{
	char buf[256] = {0};
	ULONG uRet = STAT_SUCCESS;

    signal_register();

	if (argc != 3)
	{
		printf("Usage: ./unixSockSrv <type [0:stream| 1: dgram]> <Path>\n");
		return -1;
	}

	if (atoi(args[1]) != APP_LIB_SOCKET_TYPE_UNIX_STREAM && atoi(args[1]) != APP_LIB_SOCKET_TYPE_UNIX_DGRAM)
	{
		printf("Usage: ./unixSockSrv <type [0:stream| 1: dgram]> <Path>\n");
		return -1;
	}

	gstSrvSock.enType = atoi(args[1]);
	uRet = AppLibSockUnix_SrvCreate(gstSrvSock.enType, args[2], &gstSrvSock);
	if (uRet != STAT_SUCCESS)
	{
		return -2;
	}

    while (1)
    {
        if (gstSrvSock.enType == APP_LIB_SOCKET_TYPE_UNIX_STREAM)
        {
            uRet = AppLibSock_Accept(&gstSrvSock, &gstCliSock);
            if (uRet != STAT_SUCCESS)
            {
                continue;
            }
        }

        while (1)
        {
            memset(buf, 0, sizeof(buf));
            if (gstSrvSock.enType == APP_LIB_SOCKET_TYPE_UNIX_STREAM)
            {
                uRet = AppLibSock_Recv(&gstCliSock, buf, sizeof(buf), 0);
            }
            else
            {
                uRet = AppLibSock_Recv(&gstSrvSock, buf, sizeof(buf), 0);
            }

            if (uRet != STAT_SUCCESS)
            {
                continue;
            }

            printf("---------[%s]\n", buf);

            if (strcmp(buf, "quit") == 0)
            {
                if (gstSrvSock.enType == APP_LIB_SOCKET_TYPE_UNIX_STREAM)
                {
                    AppLibSock_Close(&gstCliSock);
                }
                break;
            }
        }
    }

	return 0;
}

